package com.wm.practice;

import java.util.concurrent.*;

/**
 * @ClassName: FutureThreadPollDemo
 * @Description: 线程池处理异步任务
 * @Author: Deamer
 * @Date: 2022/8/28 10:29
 **/
public class FutureThreadPollDemo {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
//        serialExe();
        parallelExe();
        long endTime = System.currentTimeMillis();
        System.out.println("------consoleTime:" + (endTime - startTime) + "毫秒");
    }

    // 3个任务开启多个异步任务线程处理，大概用时多少？553ms
    private static void parallelExe() {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        FutureTask<String> task1 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(500);
            return "task1 over";
        });
        threadPool.submit(task1);

        FutureTask<String> task2 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(300);
            return "task2 over";
        });
        threadPool.submit(task2);

        FutureTask<String> task3 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(300);
            return "task3 over";
        });
        threadPool.submit(task3);
        try {
            task1.get();
            task2.get();
            task3.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        threadPool.shutdown();
    }

    // 3个任务1个main线程处理，大概用时多少？ 1132ms
    private static void serialExe() {
        try {
            TimeUnit.MILLISECONDS.sleep(500);
            TimeUnit.MILLISECONDS.sleep(300);
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "\t enf");
    }
}
